package com.kern.academic.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kern.academic.bean.ResponseResult;
import com.kern.academic.util.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by caoshi at 7:51 2021-06-29
 */
public class AuthInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    public static final String header_token_key = "Authorization";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ResponseResult result = new ResponseResult();
        // 在请求头里获取token
        String token = request.getHeader(header_token_key);
        logger.info(">>>>>>>>>>>>>> 在请求头中获取token信息: {}", token);
        try {
            DecodedJWT verify = JWTUtil.verify(token);
            return true;    // 放行
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            result.setMessage("无效签名");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            result.setMessage("token 过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            result.setMessage("token 算法不一致");
        } catch (Exception e) {
            result.setMessage("请登录!");
        }
        result.setCode(-1);

        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

        return false;
    }
}
